import 'package:flutter/material.dart';
import 'res/listData.dart';
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: GridViewBuilers(),
      ),
    );
  }
}
 

// GridView.builder 与 ListView.builder 方法是一样的
class GridViewBuilers extends StatelessWidget {
  Widget _getData(context,index){
     return Container(
        child:Column(
          children: <Widget>[
            Image.network(listData[index]['imageUrl']),
            SizedBox(height: 12),  //设置高度
            Text(
              listData[index]['title'],
              textAlign: TextAlign.center,
              overflow:TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 16
              ),
            )
          ],
        ),
        decoration: BoxDecoration(
          border:Border.all(
            color: Colors.blue
          )
        ),
      );
  }

  @override
  Widget build(BuildContext context) {
     
    return Container(
      padding:EdgeInsets.all(10),
      child: GridView.builder(
        // gridDelegate 必须要加  否则报错
        // 1.如要加与GridView.count 一样的参数的话就加上 SliverGridDelegateWithFixedCrossAxisCount 
        // 2.但他是没有padding 可以在 GridView.builder 上一层添加Container => padding 来替代
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, // 一行多少列
            crossAxisSpacing: 10.0,  // 水平之间间距  
            mainAxisSpacing: 10.0, //   垂直之间间距
        ),
        itemCount: listData.length,
        itemBuilder:this._getData
      ),
    );
  }
}
class GridViewCount extends StatelessWidget {
  List<Widget> _getData(){
    var tempList = listData.map((value){
      return Container(
        child:Column(
          children: <Widget>[
            Image.network(value['imageUrl']),
            SizedBox(height: 12),  //设置高度
            Text(
              value['title'],
              textAlign: TextAlign.center,
              overflow:TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 16
              ),
            )
          ],
        ),
        decoration: BoxDecoration(
          border:Border.all(
            color: Colors.blue
          )
        ),
      ); 
    });
    return tempList.toList();
  }
  @override
  Widget build(BuildContext context) {
     
    return GridView.count(
      padding:EdgeInsets.all(10), //内边距
      // reverse:true,  //组件反向排序
      shrinkWrap:true,   // 处理listview嵌套报错
      crossAxisCount: 2, // 一行多少列
      crossAxisSpacing: 10.0,  // 水平之间间距  
      mainAxisSpacing: 10.0, //   垂直之间间距
      // childAspectRatio: 1,    //  子 Widget 宽高比例
      children: this._getData(),
      // physics: NeverScrollableScrollPhysics(),      // 处理GridView中滑动父级Listview无法滑动
    );
  }

}